import { Injectable } from '@angular/core'
import { HttpClient, HttpParams } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { catchError, map } from 'rxjs/operators'

import { SERVER_URL } from 'app/utils/contraints'
import { generateOptions } from 'app/utils/helpers'
import { ObservableStore } from '@shared/classes/ObservableStoreClass'
import { GroupCommon } from '@shared/interfaces/group'

@Injectable({
  providedIn: 'root'
})
export class CommonGroupService {
  private defaultParams = {
    keyword: '',
    limit: 100,
  }

  constructor(
    private http: HttpClient,
  ) {}

  viewGroup$ = new ObservableStore(new GroupCommon())

  setViewingGroup(group: GroupCommon) {
    this.viewGroup$.setValue(group)
  }

  get viewingGroup() {
    return this.viewGroup$.value
  }

  queryGroups(params = this.defaultParams, filterMap = {}): Observable<any> {
    const url = `${SERVER_URL}/list`
    const options = generateOptions(params)

    const body = {
      codeField: 'agentCode',
      colName: 'agent.new',
      filterMap,
      nameField: 'agentName',
    }

    return this.http.post<any>(url, body, options).pipe(
      map(res => {
        return this.trans(res)
      }),
      catchError(err => throwError(err))
    )
  }

  private trans(arr) {
    return arr.map(a => {
      return { localName: a.name, label: a.name + '  ' + a.code, value: a.code }
    })
  }

}
